<template>
  <div class="search-div">
    <!-- 搜索表单 -->
    <el-form label-width="70px" size="small">
      <el-row>
        <el-form-item label="描述搜索">
          <el-input v-model.trim="queryDto.desc" style="width: 100%" placeholder="轮播图描述"></el-input>
        </el-form-item>
        <el-form-item label="状态选择">
          <el-select v-model="queryDto.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" value="1"></el-option>
            <el-option label="停用" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-row>

      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="debouncedSearchbanner">
          搜索
        </el-button>
        <el-button size="small" @click="debouncedResetbanner">重置</el-button>
      </el-row>
    </el-form>
  </div>

  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow">添 加</el-button>
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" :before-close="cancelOperate">
    <el-form label-width="130px" label-height="200px">
      <el-form-item label="轮播图描述">
        <el-input v-model.trim="UpdateDto.desc" />
      </el-form-item>
      <el-form-item label="轮播图地址">
        <UploadImage :image-url="UpdateDto.imageSrc" :old-files="oldFiles" @uploadSuccess="handleUploadSuccess" />
      </el-form-item>
      <el-form-item label="跳转链接">
        <el-input v-model.trim="UpdateDto.jumpLink" />
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model.number="UpdateDto.sort" style="width: 30%" />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="UpdateDto.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">提交</el-button>
        <el-button @click="cancelOperate">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>


  <!--表格数据-->
  <el-table :data="list" style="width: 100%">
    <el-table-column label="序号" #default="scope" width="60" align="center">
      {{ (queryDto.pageNum - 1) * queryDto.pageSize + scope.$index + 1 }}
    </el-table-column>
    <el-table-column prop="id" label="ID" v-if="false" />
    <el-table-column prop="desc" label="轮播图描述" align="center" />
    <el-table-column prop="imageSrc" label="轮播图地址" #default="scope" align="center" width="100">
      <!-- <img v-if="scope.row.imageSrc" :src="scope.row.imageSrc" alt="轮播图地址" class="banner_icon" > -->
      <el-image :src="scope.row.imageSrc" class="product_banner" fit="contain" />

    </el-table-column>
    <el-table-column prop="sort" label="排序" align="center" />
    <el-table-column prop="status" label="状态" #default="scope" align="center" width="100">
      <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
      <el-tag v-else type="danger">停用</el-tag>
    </el-table-column>
    <el-table-column label="操作" align="center" width="300" #default="scope">
      <el-button type="primary" size="small" @click="editShow(scope.row)">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="remove(scope.row.id)">
        删除
      </el-button>
      <el-button type="success" size="small" plain>
        <a :href="scope.row.jumpLink" target="_blank" class="link-button">跳转链接</a>
      </el-button>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="queryDto.pageNum"
    v-model:page-size="queryDto.pageSize"
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useApp } from "@/pinia/modules/app";
// import { GetbannerListByPage, Addbanner, Updatebanner, Deletebanner } from '@/api/product/banner';
import BannerApi from "@/api/product/banner";
import FileApi from "@/api/product/file";
import { BASE_URL } from "@/utils/request";
import { deepClone } from "@/utils/index";
import { debounce } from "@/utils";
import UploadImage from "@/components/UploadImage/uploadImage.vue";


//页面数据模版
const list = ref([]);

//分页数据总数
const total = ref(0);

//搜索分页对象
const queryDto = ref({
  pageNum: 1,
  pageSize: 10,
  desc: "",
  status: ""
});

//页面变化
const handleSizeChange = size => {
  queryDto.value.pageSize = size;
  fetchData();
};
const handleCurrentChange = number => {
  queryDto.value.pageNum = number;
  fetchData();
};


onMounted(() => {
  fetchData();
});
//分页查询和按条件查询
const fetchData = async () => {

  console.log("queryDto.value", queryDto.value.status);
  try {
    const response = await BannerApi.page(queryDto.value);
    console.log("Fetched data:", response);
    if (response && response.data) {
      const { data } = response;
      list.value = data.records || [];
      total.value = data.total || 0;
      console.log("Fetched data:", data);
    } else {
      console.error("No data returned from API");
      list.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};

const UpdateDto = ref({
  id: "",
  desc: "",
  status: "",
  jumpLink: "",
  businessId: "",
  imageSrc: "",
  sort: ""
});


//增删改-------------------------

const dialogVisible = ref(false);
const banner = ref(UpdateDto);
//深拷贝,打开弹窗
const addShow = () => {

  banner.value = deepClone(UpdateDto.value);

  dialogVisible.value = true;
};
const searchbanner = () => {
  fetchData();
};

//显示修改窗口
const editShow = (row) => {
  banner.value = deepClone(row);
  dialogVisible.value = true;
};

// 缓存已上传的图片
let oldFiles = ref([]);
// 取消表单操作
const cancelOperate = () => {
  UpdateDto.value = {};
  // 删除之前上传的图片
  if (oldFiles.value.length > 0) {
    FileApi.remove(oldFiles.value);
  }
  oldFiles.value = [];
  dialogVisible.value = false;
};


//提交保存与修改
const saveOrUpdate = async () => {
  //描述不能为空
  if (!UpdateDto.value.desc) {
    ElMessage.info("描述不能为空");
    return;
  }
  //图片不能为空
  if (!UpdateDto.value.imageSrc) {
    ElMessage.info("图片不能为空");
    return;
  }

  //跳转链接不能为空
  if (!UpdateDto.value.jumpLink) {
    ElMessage.info("跳转链接不能为空");
    return;
  }
  //排序不能为空
  if (!UpdateDto.value.sort) {
    ElMessage.info("排序不能为空");
    return;
  }


  await BannerApi.operate(UpdateDto.value);
  // 删除之前上传的冗余图片
  FileApi.remove(oldFiles.value.filter(src => src !== UpdateDto.value.imageSrc));
  oldFiles.value = [];
  dialogVisible.value = false;
  ElMessage.success("操作成功");
  dialogVisible.value = false;
  cancelOperate();
  fetchData();
};


//删除
const remove = async (id) => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      await BannerApi.removeById(id);
      ElMessage.success("删除成功");
      fetchData();
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};
// ===================== 上传操作 ==========================
const handleUploadSuccess = imgSrc => {
  UpdateDto.value.imageSrc = imgSrc;
  oldFiles.value.push(imgSrc);
};

//重置搜索框
const resetData = () => {
  queryDto.value.desc = "";
  queryDto.value.status = "";
  //刷新页面
  fetchData();
};

const debouncedSearchbanner = debounce(searchbanner, 300);
const debouncedResetbanner = debounce(resetData, 300);


</script>

<style scoped>
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 6px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 22px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}

.link-button {
  color: inherit;
  /* 继承按钮的颜色 */
  text-decoration: none;

}

.el-button--success.is-plain .link-button {
  color: #41b707;
}

.el-button--success.is-plain .link-button:hover {
  color: #5baa2e;
}

</style>
